package net.qiqbframework.modelling.recording;

import lombok.extern.slf4j.Slf4j;
import net.qiqbframework.commandhandling.CommandMessage;
import net.qiqbframework.common.security.AuthUserProvider;
import net.qiqbframework.modelling.command.AggregateHandlingMonitor;
import org.javers.core.Javers;
import org.javers.core.commit.Commit;

/**
 * 聚合变化记录
 */
@Slf4j
public class AggregateChangesRecorder implements AggregateHandlingMonitor {

    private final AuthUserProvider authUserProvider;

    private final Javers javers;

    public AggregateChangesRecorder(AuthUserProvider authUserProvider, Javers javers) {
        this.authUserProvider = authUserProvider;
        this.javers = javers;
    }

    @Override
    public <T> void afterCommit(CommandMessage<?> commandMessage, T beforeHandleAggregateRoot, T afterHandleAggregateRoot) {
        final Commit commit = javers.commit(authUserProvider.getAuthUser(), afterHandleAggregateRoot);

        log.info("用户[{}]执行命令[ {}]。\n影响了聚合根对象：{}", commit.getAuthor(), commandMessage.toString(), commit.getChanges().prettyPrint());
    }
}
